package com.masiyi.springai.service.impl;/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import com.alibaba.cloud.ai.tongyi.chat.TongYiChatOptions;
import com.masiyi.springai.domain.Customer;
import com.masiyi.springai.domain.Knowledge;
import com.masiyi.springai.service.AbstractTongYiServiceImpl;
import com.masiyi.springai.service.CustomerService;
import com.masiyi.springai.service.KnowledgeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.StreamingChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * The Chat simple example service implementation.
 * There is optional message parameter whose default value is "Tell me a joke".
 * pl The response to the request is from the TongYi models Service.
 *
 * @author yuluo
 * @author <a href="mailto:yuluo08290126@gmail.com">yuluo</a>
 * @since 2023.0.0.0
 */

@Service
public class TongYiSimpleServiceImpl extends AbstractTongYiServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(TongYiSimpleServiceImpl.class);

    private final ChatModel chatModel;

    private final StreamingChatModel streamingChatModel;
    private final CustomerService customerService;
    private final KnowledgeService knowledgeService;

    @Autowired
    public TongYiSimpleServiceImpl(ChatModel chatModel, StreamingChatModel streamingChatModel,
                                   CustomerService customerService, KnowledgeService knowledgeService) {
        this.customerService = customerService;
        this.chatModel = chatModel;
        this.streamingChatModel = streamingChatModel;
        this.knowledgeService = knowledgeService;
    }

    @Override
    public String completion(String message) {
        Customer customer = new Customer();
        customer.setRole(1);
        customer.setContent(message);
        customerService.save(customer);
        Prompt prompt = new Prompt(new UserMessage(message));
        String content = chatModel.call(prompt).getResult().getOutput().getContent();
        Customer customer2 = new Customer();
        customer2.setRole(2);
        customer2.setContent(content);
        customerService.save(customer2);
        return content;
    }

    String promptTemplate = """
            你是一位专业的客服代表，负责解答用户关于产品的各种问题。以下是用户的问题和我们已有的产品知识：

            用户问题: %s

            产品知识:
            %s

            请根据以上信息回答用户的问题。
            """;

    /**
     * 处理知识查询请求
     *
     * 本方法模拟了一个知识查询的过程，涉及到用户请求的保存、知识库的查询以及基于这些信息生成回复
     * 它首先创建了一个表示用户请求的Customer对象，然后根据这个请求获取相应的知识信息，
     * 最后生成并返回一个包含知识信息的回复
     *
     * @param message 用户的查询消息，用于检索知识库
     * @return 根据知识库生成的回复内容
     */
    @Override
    public String knowledge(String message) {
        // 创建一个表示用户请求的Customer对象，并设置其角色和内容
        Customer customer = new Customer();
        customer.setRole(1);
        customer.setContent(message);
        // 保存用户请求到数据库
        customerService.save(customer);

        // 从知识库中获取所有知识信息
        List<Knowledge> list = knowledgeService.list();
        // 提取所有知识内容并合并为一个字符串
        String productKnowledge = list.stream().map(Knowledge::getKnowledge).reduce((a, b) -> a + "\n" + b).orElse("");

        // 根据用户消息和知识库内容格式化提示模板
        String format = String.format(promptTemplate, message, productKnowledge);
        // 创建一个Prompt对象，用于生成回复
        Prompt prompt = new Prompt(new UserMessage(format));

        // 调用聊天模型生成回复内容
        String content = chatModel.call(prompt).getResult().getOutput().getContent();

        // 创建一个表示系统回复的Customer对象，并设置其角色和内容
        Customer customer2 = new Customer();
        customer2.setRole(2);
        customer2.setContent(content);
        // 保存系统回复到数据库
        customerService.save(customer2);

        // 返回生成的回复内容
        return content;
    }


    @Override
    public List<Customer> history() {
        return customerService.list();
    }

    @Override
    public Map<String, String> streamCompletion(String message) {

        StringBuilder fullContent = new StringBuilder();

        streamingChatModel.stream(new Prompt(message))
                .flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults()))
                .map(content -> content.getOutput().getContent())
                .doOnNext(fullContent::append)
                .last()
                .map(lastContent -> Map.of(message, fullContent.toString()))
                .block();

        logger.info(fullContent.toString());

        return Map.of(message, fullContent.toString());
    }

    @Override
    public Flux<ServerSentEvent> flux(String message) {
        TongYiChatOptions chatOptions = new TongYiChatOptions();
        chatOptions.setIncrementalOutput(true);
        Flux<ServerSentEvent> streamEvents = streamingChatModel.stream(new Prompt(message, chatOptions))
                .map(outputContent -> {
                    String content = outputContent.getResult().getOutput().getContent();
                    System.out.println(content);
                    return ServerSentEvent.builder().event("message").data(content).build();
                });
        // 返回 Flux<ServerSentEvent>
        return streamEvents;

    }

}
